package com.hdl.school.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ParseException;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.leectrl.utils.Bus;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.io.UnsupportedEncodingException;
import java.util.Date;

public class CloudCtrlService extends Service {
    private MqttClient mqttClient;
    private String deviceId;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    if(mqttClient==null||(!mqttClient.isConnected())){
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                connectMqttServer();
                            }
                        }).start();
                    }
                    handler.sendEmptyMessageDelayed(0,20000);
                    break;
            }
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        SharedPreferences sharedPreferences=getSharedPreferences("school_iot", 0);
        deviceId=sharedPreferences.getString("DEVICEID",null);
        handler.sendEmptyMessageDelayed(0,20000);
        new Thread(new Runnable() {
            @Override
            public void run() {
                connectMqttServer();
            }
        }).start();

        Bus.getInstance().on("publish_feedback_msg", new Bus.MessageEvent() {
            @Override
            public void onEvent(String key, Object... message) {
                JSONObject obj = (JSONObject) message[0];
                publishMessage("/public/iot/"+deviceId+"/status",JSON.toJSONString(obj));
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeMessages(0);
    }

    private  void connectMqttServer() {
        Log.e("CloudCtrlService","连接MQTT：112.74.162.18");
        if (mqttClient != null) {
            try {
                mqttClient.close(true);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        try {
            mqttClient = new MqttClient("tcp://112.74.162.18:1883", "terminal_"+(new Date()).getTime(), new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName("leectrl_terminal");
            options.setPassword("LikongTerminal2018".toCharArray());
            // 设置超时时间
            options.setConnectionTimeout(10);
            // 设置会话心跳时间
            options.setKeepAliveInterval(20);
            options.setAutomaticReconnect(false);
            mqttClient.connect(options);
            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    Log.e("CloudCtrlService", "onDisconnected");
                }

                @Override
                public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                    String topicStr = topic;
                    String payloadStr = null;
                    try {
                        payloadStr = (new String(mqttMessage.getPayload(), "UTF-8"));
                        Log.e("CloudCtrlService", topicStr + "==>" + payloadStr);
                        if(topicStr.endsWith("/ctrl")){
                            JSONObject contentObj=JSON.parseObject(payloadStr);
                            Bus.getInstance().emit("exec_action", contentObj.getString("action"), contentObj.getJSONObject("params"), contentObj.getString("portType"), 3);
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }

            });
            Log.e("CloudCtrlService", "onConnected");
            subscribeTopic("/public/iot/"+deviceId+"/ctrl");
        }catch (Exception e) {
            e.printStackTrace();
        }


    }

    public void publishMessage(String topic,String msg){
        try {
            if(mqttClient.isConnected()){
                MqttMessage message = new MqttMessage();
                message.setQos(1);
                message.setRetained(true);
                message.setPayload(msg.getBytes());
                MqttTopic mqttTopic = mqttClient.getTopic(topic);
                MqttDeliveryToken token = mqttTopic.publish(message);//发布主题
                token.waitForCompletion();
            }

        } catch (MqttPersistenceException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (MqttException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }




    public  void subscribeTopic(String topicStr) {
        // Subscribe to a topic foo
        try {
            mqttClient.subscribe(topicStr);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public  void unsubscribeTopic(String topicStr) {
        // Subscribe to a topic foo
        try {
            mqttClient.unsubscribe(topicStr);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}
